import React from 'react';
import {
	ActivityIndicator,
	Alert,
	Dimensions,
	Image,
	PixelRatio,
	StyleSheet,
	Text,
	TouchableOpacity,
	View,
} from 'react-native';
import Toast from './component/Toast';
import axiosInstance from './utils/request';
import DraggableFlatList, {ScaleDecorator} from "react-native-draggable-flatlist";

let rows=20;//
let totalPage=0;//总的页数
let {width,height} = Dimensions.get('window');



class CustInfoOrderScene extends React.Component {

	constructor(props) {
    	super(props);
		const { params } = this.props.route;
		let bookId=params.bookId;
		let bookName=params.bookName;
		this.state = {
			dataArray: [],
			page:1,
			isLoading: true,
			bookId:bookId,
			bookName:bookName
	 	};

  	}

  	componentDidMount() {
		this.props.navigation.setOptions({
			title: '客户顺序调整',
		})
		this.fetchData(this.state.bookId);
	}

	/*
		因为服务端modified字段代表的是时间戳，所以Max(anchor)表示客户端最近一次同步的时间，如果存在服务端modified > Max(anchor),
		说明服务端需要向客户端同步数据。
	*/
	fetchData(bookId){
		let url=global.server.url+'/custInfo/selectListPageByBookId';
		axiosInstance({
		  method: 'post',
		  url: url,
		  data: {
			bookId:bookId,
			pageVO:{
				page:1,
				rows:1000
			}
		  }
		})
        .then(res => {
			let datas = [];
			let count=res.records.length;
			totalPage=res.pages;
			datas = datas.concat(res.records);

            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            datas.map(function (item,index) {
            	dataBlob.push({
					key:`item-${index}`,
                    custCode:item.custCode,
                    custName:item.custName,
					tel:item.tel,
					orderNum:item.orderNum,
					address:item.address
                })
            });
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }

            this.setState({
                //复制数据源
            	//  dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray.concat( dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				count:count,
				order:Object.keys(dataBlob) //Array of keys
            });
            datas = null;//重置为空
            dataBlob = null;
        })
        .catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			console.log(error);
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	updateOrder(){
		let URL=global.server.url+'/custInfo/updateOrder';
		axiosInstance.post(URL,
			{
				list:JSON.stringify(this.state.dataArray)
			}
		).then(res => {
			let datas = [];
			datas = datas.concat(res);
			if(datas>0){
				Toast.show("顺序调整成功！");
			}
			this.setState({
                //复制数据源
            	//  dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray,
				order:Object.keys(this.state.dataArray) //Array of keys
            });
        }).catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	//加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    renderItem = ({ item, drag, isActive })=>{

		console.log(item);
		console.log(isActive);
		return (
			<ScaleDecorator>
				<TouchableOpacity
					style={[{flexDirection:'row'},styles.menulineCenter]}
					onLongPress={drag}
					disabled={isActive}
				>
					<View style={styles.items}>
						<TouchableOpacity
							underlayColor={'#eee'}
							style={{
								padding:4,
								borderColor: '#eee',
							}}

						>
							<View style={styles.rightContainer}>
								<Image style={styles.image} source={require('../img/arrow.png')}/>
								<Text style={{fontSize:16,marginTop:10,fontWeight:"bold"}}>{item.orderNum}</Text>
							</View>
						</TouchableOpacity>
						<View>
							<Text style={{fontSize:14}}>{item.custCode}</Text>
							<Text style={{fontSize:14}}>{item.custName}</Text>
							<Text style={{fontSize:14}}>{item.tel}</Text>
							<Text style={{fontSize:14}}>{item.address}</Text>
						</View>
					</View>
				</TouchableOpacity>
			</ScaleDecorator>
		)
	}

	render() {
		if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        }
		return (
			<View style={styles.container}>
				<View style={{flex:1}}>
					<DraggableFlatList
						data={this.state.dataArray}
						keyExtractor={(item) => item.key}

						renderItem={this.renderItem}
						onDragEnd={({data})=>{
							// console.log('drag end:',data);
							this.setState({
								dataArray:data
							})
							this.updateOrder()
						}}
					/>
				</View>



				  <View style={{
						height:30,
						flexDirection:'row',
						alignItems:'center',
						borderBottomWidth:1,
						borderBottomColor:'#D7D7D7',
						backgroundColor:"#F5FCFF",
						paddingLeft:6
					}}>
						<View style={styles.flex}>
							<Text style={styles.headerText}>{this.state.bookName}</Text>
						</View>
						<View style={styles.flex}>
							<Text style={styles.headerText}>用户数：{this.state.count}</Text>
						</View>
				  </View>
		   </View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#F5FCFF',
    },
	image:{
		marginLeft:5,
		marginTop:6,
		height:40,
		width:40,
	},
	items: {
        flexDirection: 'row',
        alignItems: 'center',
        margin: 3,
    },
	bottomStyle:{
		flex:1,
        fontSize:16,
        fontWeight:"bold",
        textAlign:"right",
		marginTop:5,
		marginRight:10,
    },
	flex:{
    	flex:1
  	},
	headerText: {
        fontSize: 15,
        textAlign: 'left',
        margin: 5
    },
	menulineCenter:{
		borderBottomWidth:1/PixelRatio.get(),
		borderColor:'#d0d0d0'
	},
    rightContainer: {
    	flex: 1,
  	},
});

export default CustInfoOrderScene
